package testwebsocketserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class RequestProcessor extends Thread
{
    private String TAG = "Unnamed";
    private Socket clientSocket;
    
    public RequestProcessor(String name, Socket clientSocket)
    {
        super(name);
        TAG = name;
        this.clientSocket = clientSocket;
    }
    
    public void run()
    {
        int readByte;
        StringBuilder line = new StringBuilder();
        String readLine;
        try
        {
            clientSocket.setSoTimeout(2500);
            
           try(BufferedReader istream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())))
            {
                readLine = istream.readLine();
                if (readLine != null)
                {
                    HttpRequest request = new HttpRequest(readLine);
                    // TODO Handling exceptions from HttpRequest class
                    request.readHeaders(istream);
                    log(request); // Show all read data
                    if (request.isWebsocketHandshakeRequest())
                    {
                        log("Websocket");
                    }
                    else
                    {
                        log("Not websocket");
                    }
                }
            }
            catch (IOException ex)
            {
                log(ex);
            }
            clientSocket.close();
            log("Connection lost");
        }
        catch (IOException ex)
        {
            log(ex);
        }
    }
    
    private void log(Object ob)
    {
        System.out.println(TAG + ": " + String.valueOf(ob));
    }
}
